package eteam.aps.systemservice.dal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import eteam.aps.common.entity.ParentEntity;
import eteam.aps.systeminterface.model.entity.MailEntity;
import eteam.aps.systemservice.dal.mapper.IMailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class MailDal {

    @Autowired
    private IMailMapper mapper;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送简单邮箱
     *
     * @param to      发给某人
     * @param content 内容
     */
    public void sendSimple(String to, String content) throws MessagingException {
        MailEntity mailEntity = mapper.selectOne(new LambdaQueryWrapper<MailEntity>()
                .select(MailEntity::getFSubject, MailEntity::getFUsername, MailEntity::getFSuffix, MailEntity::getIsHtml)
                .ne(MailEntity::getfState, ParentEntity.FSTATE_DELETED).last("LIMIT 0,1"));
        MimeMessage message = javaMailSender.createMimeMessage();
        // 不开启附件功能 设置中文
        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
        //主题
        helper.setSubject(mailEntity.getFSubject());
        //内容
        String fSuffix = mailEntity.getFSuffix();
        String[] split = fSuffix.split("%s");
        String[] contents = content.split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length - 1; i++) {
            sb.append(split[i]).append(contents[i]);
        }
        sb.append(split[split.length - 1]);
        helper.setText(sb.toString(), mailEntity.getIsHtml() == 1);
        //收件人
        helper.setFrom(mailEntity.getFUsername());
        helper.setTo(to);
        javaMailSender.send(message);
    }

}
